"""
@author: yinjx
@file: search.py
@time: 2023/8/5 16:40
"""
from flask import Blueprint, request
from flask_restful import Api, Resource
from libs.response import generate_response
from . import keysearch_bp
import json
from flask import Blueprint, request
from flask_restful import Api, Resource
from models import db
from libs.auth import auth_required
from libs.handler import default_error_handler
from models.user import Book
from sqlalchemy import or_
from flask import jsonify
# 将restful api对象和蓝图绑定
api = Api(keysearch_bp)
class BookSearch(Resource):
    #@auth_required
    def get(self):
        keyword = request.args.get('keyword')
        print(keyword)

        if keyword:
            books = Book.query.filter(or_(Book.title == keyword, Book.author == keyword)).all()
            if books:
                result = []
                for book in books:
                    book_data = {
                        'id': book.id,
                        'author': book.author,
                        'title': book.title,
                        'cover': book.cover,
                        'description': book.description
                    }
                    result.append(book_data)
            result_str = json.dumps(result, ensure_ascii=False)
            return generate_response(data=json.loads(result_str), message="get success!")
        return generate_response(code=1009, message="data empty!")
api.add_resource(BookSearch, "/search/book", endpoint="keysearch")






